package com.bc.bcsellerapihttp.common;

import com.bc.bcapi.service.T_ProjectService;
import com.bc.bcapi.service.T_User_seller_infoService;
import com.bc.bccore.redis.RedisService;
import com.bc.bccore.webconfig.WebConfig;
import com.bc.bcmodel.BuyerUserInfo;
import com.bc.bcmodel.SellerUserInfo;
import com.bc.bcmodel.consts.GlobalSettings;
import com.bc.bcmodel.consts.RedissCacheKey;
import com.bc.bcmodel.domain.T_Mnguser_infoModel;
import com.bc.bcmodel.domain.T_ProjectModel;
import com.bc.bcmodel.domain.T_User_seller_infoModel;
import com.bc.bcmodel.resp.UserCookieResp;
import com.bc.commoncore.security.AES;
import com.bc.commoncore.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.concurrent.TimeUnit;

/**
 * @Name UserContext
 * @Description
 * @Author douhaichao
 * @Date 2018/8/17 22:58
 * @Version 1.0
 **/
public class UserContext {
    protected static final Logger LOGGER = LoggerFactory.getLogger(UserContext.class);
    private final static RedisService redisService;
    private final static T_User_seller_infoService t_User_seller_infoService;
    private final static T_ProjectService t_ProjectService;

    static {
        redisService = SpringBeanHelper.getCustomBeanByType(RedisService.class);
        t_User_seller_infoService = SpringBeanHelper.getCustomBeanByType(T_User_seller_infoService.class);
        t_ProjectService = SpringBeanHelper.getCustomBeanByType(T_ProjectService.class);
    }

    private UserContext(SellerUserInfo req) {
        this.loginInfo = req;
    }

    SellerUserInfo loginInfo;

    public static boolean checkIsLogin() {
        return getCurrentContext() != null;
    }

    public static boolean checkIsAllow(int userId, String url) {
        return true;
    }

    public SellerUserInfo getLoginInfo() {
        return this.loginInfo;
    }

    public static UserContext getCurrentContext() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String user_id = "";
        String cookieValue = CookieUtils.getCookie(request, GlobalSettings.SELLER_COOKIENAME);
        if (cookieValue == null || cookieValue.trim().isEmpty()) {
            return getContext(user_id);
        }
        try {
            String uinfo = URLDecoder.decode(cookieValue.trim(), "UTF-8");
            uinfo = AES.aesDecrypt(uinfo);
            UserCookieResp resp = JsonUtil.str2obj(uinfo, UserCookieResp.class);
            user_id = resp.getUser_id();
        } catch (Exception e) {
        }
        return getContext(user_id);

    }

    private static UserContext getContext(String user_id) {
        try {
            if (StringUtils.isEmpty(user_id)) {
                return new UserContext(null);
            }

            SellerUserInfo model = getUserInfoFromRedis(user_id);
            if (model == null) {
                T_User_seller_infoModel m = new T_User_seller_infoModel();
                m.setUser_id(user_id);
                T_User_seller_infoModel t_user_seller_infoModel = t_User_seller_infoService.findByNamedParam(m);
                model = new SellerUserInfo();
                model.setUser_id(t_user_seller_infoModel.getUser_id());
                model.setEmail(t_user_seller_infoModel.getEmail());
                model.setHead_figure(WebConfig.getImgUrl()+ t_user_seller_infoModel.getHead_figure());
                model.setName(t_user_seller_infoModel.getName());
                model.setNick_name(t_user_seller_infoModel.getNick_name());

                T_ProjectModel t_projectModel = new T_ProjectModel();
                t_projectModel.setUser_id(user_id);
                T_ProjectModel t_projectModelResult = t_ProjectService.findByNamedParam(t_projectModel);
                if (t_projectModelResult != null) {
                    model.setProjectId(t_projectModelResult.getPid());
                    model.setProjectStatus(t_projectModelResult.getStatus());
                }
                setUserInfoToRedis(model, user_id);
            }
            return new UserContext(model);
        } catch (Exception e) {
            LOGGER.error("根据解密后的cookie解析用户信息时失败:" + e.getMessage() + StringUtils.getStackTrace(e));
            return new UserContext(null);
        }
    }

    private static SellerUserInfo getUserInfoFromRedis(String user_id) {
        try {
            String key = RedissCacheKey.Seller_UserInfo_Key + user_id;
            String userInfoStr = redisService.get(key);
            if (userInfoStr != null) {
                return JsonUtil.str2obj(userInfoStr, SellerUserInfo.class);
            }
            return null;
        } catch (Exception e) {
            LOGGER.error("get userinfo from redis fail :" + e.getMessage() + StringUtils.getStackTrace(e)+",user_id["+user_id+"]");
            return null;
        }
    }

    private static void setUserInfoToRedis(SellerUserInfo model, String user_id) {
        try {
            String key = RedissCacheKey.Seller_UserInfo_Key + user_id;
            String userStr = JsonUtil.obj2string(model);
            redisService.set(key, userStr, 5, TimeUnit.MINUTES);
        } catch (Exception e) {
            LOGGER.error("set userinfo from redis fail :" + e.getMessage() + StringUtils.getStackTrace(e)+",user_id["+user_id+"]");
        }
    }

}
